package com.nowcoder.community.controller;

import com.nowcoder.community.entity.*;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.service.CommentService;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.constant.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import com.nowcoder.community.util.RedisKeyUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author 花木凋零成兰
 * @date 2024/3/14 18:42
 */
@Controller
@RequestMapping("/discuss")
public class DiscussPostController {

    @Resource
    private DiscussPostService discussPostService;

    @Resource
    private HostHolder hostHolder;

    @Resource
    private UserService userService;

    @Resource
    private CommentService commentService;

    @Resource
    private LikeService likeService;

    @Resource
    private EventProducer eventProducer;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 新增帖子
     * @param title
     * @param content
     * @return
     */
    @RequestMapping(path = "/add", method = RequestMethod.POST)
    @ResponseBody
    public String addDiscussPost(String title, String content) {
        User user = hostHolder.getUser();
        if (user == null) {
            return CommunityUtil.getJSONString(403, "你还没有登录!");
        }

        DiscussPost discussPost = DiscussPost.builder()
                .userId(user.getId())
                .title(title)
                .content(content)
                .createTime(new Date())
                .build();
        discussPostService.addDiscussPost(discussPost);

        // TODO 报错情况将来统一处理

        // 触发发帖事件
        Event event = Event.builder()
                .topic(CommunityConstant.TOPIC_PUBLISH)
                .userId(hostHolder.getUser().getId())
                .entityType(CommunityConstant.ENTITY_TYPE_POST)
                .entityId(discussPost.getId())
                .build();
        eventProducer.fireEvent(event); // 发布事件

        // 计算帖子的分数的key
        String redisKey = RedisKeyUtil.getPostScoreKey();
        // 存储到redis的Set中 去重 重复数据会被替换
        redisTemplate.opsForSet().add(redisKey, discussPost.getId());

        return CommunityUtil.getJSONString(0, "发布成功!");
    }

    /**
     * 根据帖子id 获取帖子详情
     * @param discussPostId
     * @param model
     * @param page
     * @return
     */
    @RequestMapping(path = "/detail/{discussPostId}", method = RequestMethod.GET)
    public String getDiscussPost(@PathVariable("discussPostId") int discussPostId, Model model, Page page) {
        // 根据帖子id 获取帖子
        DiscussPost discussPost = discussPostService.findDiscussPostById(discussPostId);
        model.addAttribute("post", discussPost);

        // 查询帖子作者
        User user = userService.findUserById(discussPost.getUserId());
        model.addAttribute("user", user);
        // 获取帖子点赞
        long likeCount = likeService.findEntityLikeCount(CommunityConstant.ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeCount", likeCount);
        // 获取当前登录用户
        User currentUser = hostHolder.getUser();
        // 点赞状态
        int likeStatus = currentUser == null ? 0 :
                likeService.findEntityLikeStatus(
                currentUser.getId(), CommunityConstant.ENTITY_TYPE_POST, discussPostId
        );
        model.addAttribute("likeStatus", likeStatus);

        // 评论的分页信息
        page.setLimit(5);
        page.setRows(discussPost.getCommentCount());    // 设置评论数
        page.setPath("/discuss/detail/" + discussPostId);

        // 评论 —— 给帖子的评论
        // 回复 —— 给评论的评论
        List<Comment> commentList =     // 获取评论列表
                commentService.findCommentsByEntity(CommunityConstant.ENTITY_TYPE_POST, discussPost.getId(), page.getOffset(), page.getLimit());
        List<Map<String, Object>> commentVoList = new ArrayList<>(); // 评论Vo列表
        if (commentList != null) {
            for (Comment comment : commentList) {
                Map<String, Object> commentVo = new HashMap<>();    // 评论VO
                commentVo.put("comment", comment);  // 添加评论
                commentVo.put("user", userService.findUserById(comment.getUserId()));   // 添加评论作者

                // 评论点赞数量
                likeCount = likeService.findEntityLikeCount(CommunityConstant.ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeCount", likeCount);
                // 获取点赞状态
                likeStatus = currentUser == null ? 0 :
                        likeService.findEntityLikeStatus(
                                currentUser.getId(), CommunityConstant.ENTITY_TYPE_COMMENT, comment.getId()
                        );
                commentVo.put("likeStatus", likeStatus);

                // 获取评论的 回复列表
                List<Comment> replyList = commentService.findCommentsByEntity(
                        CommunityConstant.ENTITY_TYPE_COMMENT, comment.getId(), 0, Integer.MAX_VALUE);
                // 回复VO列表
                List<Map<String, Object>> replyVoList = new ArrayList<>();
                if (replyList != null) {
                    for (Comment reply : replyList) {
                        Map<String, Object> replyVo = new HashMap<>();
                        replyVo.put("reply", reply);    // 回复
                        replyVo.put("user", userService.findUserById(reply.getUserId()));    // 回复作者
                        // 回复的目标
                        User target = reply.getTargetId() == 0 ? null : userService.findUserById(reply.getTargetId());
                        replyVo.put("target", target);

                        // 评论点赞数量
                        likeCount = likeService.findEntityLikeCount(CommunityConstant.ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeCount", likeCount);
                        // 获取点赞状态
                        likeStatus = currentUser == null ? 0 :
                                likeService.findEntityLikeStatus(
                                        currentUser.getId(), CommunityConstant.ENTITY_TYPE_COMMENT, reply.getId()
                                );
                        replyVo.put("likeStatus", likeStatus);

                        replyVoList.add(replyVo);
                    }
                }
                commentVo.put("replys", replyVoList);   // 增加回复列表

                // 获取回复数量
                int replyCount = commentService.findCommentCount(CommunityConstant.ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("replyCount", replyCount);

                commentVoList.add(commentVo);
            }
        }
        model.addAttribute("comments", commentVoList);

        return "/site/discuss-detail";
    }

    /**
     * 将帖子置顶
     * @param id 帖子id
     * @return
     */
    @RequestMapping(path = "/top", method = RequestMethod.POST)
    @ResponseBody
    public String setTop(int id) {
        discussPostService.updateType(id, 1);

        // 触发发帖事件
        Event event = Event.builder()
                .topic(CommunityConstant.TOPIC_PUBLISH)
                .userId(hostHolder.getUser().getId())
                .entityId(id)
                .entityType(CommunityConstant.ENTITY_TYPE_POST)
                .build();
        eventProducer.fireEvent(event); // 发布事件

        return CommunityUtil.getJSONString(0);
    }

    /**
     * 将帖子 加精
     * @param id 帖子id
     * @return
     */
    @RequestMapping(path = "/wonderful", method = RequestMethod.POST)
    @ResponseBody
    public String setWonderful(int id) {
        discussPostService.updateStatus(id, 1);

        // 触发发帖事件
        Event event = Event.builder()
                .topic(CommunityConstant.TOPIC_PUBLISH)
                .userId(hostHolder.getUser().getId())
                .entityId(id)
                .entityType(CommunityConstant.ENTITY_TYPE_POST)
                .build();
        eventProducer.fireEvent(event); // 发布事件

        // 计算帖子的分数的key
        String redisKey = RedisKeyUtil.getPostScoreKey();
        // 存储到redis的Set中 去重 重复数据会被替换
        redisTemplate.opsForSet().add(redisKey, id);

        return CommunityUtil.getJSONString(0);
    }

    /**
     * 将帖子 删除
     * @param id 帖子id
     * @return
     */
    @RequestMapping(path = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public String setDelete(int id) {
        discussPostService.updateStatus(id, 2);

        // 触发 删帖 事件
        Event event = Event.builder()
                .topic(CommunityConstant.TOPIC_DELETE)
                .userId(hostHolder.getUser().getId())
                .entityId(id)
                .entityType(CommunityConstant.ENTITY_TYPE_POST)
                .build();
        eventProducer.fireEvent(event); // 发布事件

        return CommunityUtil.getJSONString(0);
    }


}
